<?php


namespace backend\models;

use common\models\User;
use Yii;
use yii\base\Model;

class PasswordForm extends Model
{
    public $password;   //新密码
    public $rePassword; // 重复新密码
    public $oldPassword;//旧密码

    private $_user;

    public function rules()
    {
        return [
            [['rePassword', 'password','oldPassword'], 'required','message'=>'不能为空!'],
            ['rePassword', 'compare', 'compareAttribute' => 'password', 'operator' => '===','message'=>'密码不一致!'],
            ['oldPassword', 'repassword']
        ];
    }


    public function repassword($attribute, $params)
    {
            $user = $this->getUser();
            if (!$user || !$user->validatePassword($this->oldPassword)) {
                $this->addError($attribute, '旧密码错误.');
            }

    }

    /**
     * 更新密码
     * @return bool
     */
    public function Uppassword(){
        if(!$this->hasErrors()){
            $user = $this->getUser();
            $user->setPassword($this->password);
            $user->updated_at = time();
            if(!$user->save()){
                return false ;
            }
            return true ;
        }
        return false ;


    }



    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    protected function getUser()
    {
        if ($this->_user === null) {
            $userId = Yii::$app->user->identity->getId();
            if($userId){
                $this->_user = User::findOne($userId);
            }
        }
        return $this->_user;
    }


}